package visit;
/**
 *
 * @author Florentini
 */
import javax.faces.application.NavigationHandler;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;

public class AuthenticationPhaseListener implements PhaseListener {
    private boolean userExists(FacesContext context) {
        ExternalContext extContext = context.getExternalContext();
        SessionBean1 session = (SessionBean1) extContext.getSessionMap().get("SessionBean1");
        if (session != null) {
            boolean tmp = (session.isEnLinea()== true);
            return tmp;
        } else {
            return false;
        }
    }
    public void beforePhase(PhaseEvent pe) {
        /*if (pe.getPhaseId() == PhaseId.RESTORE_VIEW) {
            System.out.println("Procesando nueva Peticion!");
        }
        System.out.println("before - " + pe.getPhaseId().toString());*/
    }

    public void afterPhase(PhaseEvent pe) {
        FacesContext fc = pe.getFacesContext();
        //System.out.println("after - " + pe.getPhaseId().toString() + "---" + fc.getViewRoot().getViewId());

        if (pe.getPhaseId() == PhaseId.RESTORE_VIEW) {
            //System.out.println("Miramos si esta logeado!");

            boolean loginPage = fc.getViewRoot().getViewId().lastIndexOf("Page1") > -1 ? true : false;
            if (!loginPage && !userExists(fc)) {
                fc.responseComplete();
                NavigationHandler nh = fc.getApplication().getNavigationHandler();
                nh.handleNavigation(fc, null, "LoginError");
            }
        }

        /*if (pe.getPhaseId() == PhaseId.RENDER_RESPONSE) {
            System.out.println("Peticion Procesada!");
        }*/

    }

    public PhaseId getPhaseId() {
        return PhaseId.ANY_PHASE;
    }

}
